import axios from 'axios'
import { ElMessage } from 'element-plus'
import {useUserStore} from '@/stores/user'
import { useRouter } from 'vue-router'
// 创建axios实例
const request = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 15000
})

// axios请求拦截器
request.interceptors.request.use(config => {
  // 1. 从pinia获取token数据
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
request.interceptors.response.use((response) => {
  const { result, msg, code } = response.data // 默认json格式
  if (code ==='1') {
    return result
  } else {
    ElMessage.error(msg || '未知错误')
    return Promise.reject(new Error(msg))
  }
}, e => {
  const userStore = useUserStore()
  const router = useRouter()
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })
  if(e.response.status === 401){
      userStore.clearUserInfo()
      // ElMessage({
      //   type:'error',
      //   message:'token过期,请重新登录'
      // })
      router.push('/login')
  }
  return Promise.reject(e)
})


export default request